"""
主窗口模块
实现应用程序的主界面
"""

import sys
import os
from PyQt6.QtWidgets import (
    QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QTabWidget,
    QTextEdit, QPushButton, QComboBox, QLabel, QSpinBox,
    QCheckBox, QGroupBox, QSplitter, QMenuBar, QStatusBar,
    QToolBar, QFileDialog, QMessageBox, QProgressBar,
    QApplication, QMenu, QDialog, QGridLayout, QScrollArea, QSizePolicy
)
from PyQt6.QtCore import Qt, QThread, pyqtSignal, QSettings
from PyQt6.QtGui import QFont, QIcon, QKeySequence, QTextCursor, QAction


from ..core.text_formatter import TextFormatter
from ..core.text_comparator import TextComparator
from ..core.file_handler import FileHandler
from .text_editor import TextEditor
from .diff_viewer import DiffViewer
from .search_dialog import SearchDialog


class MainWindow(QMainWindow):
    """主窗口类"""
    
    def __init__(self):
        super().__init__()
        self.diff_viewer = None
        self.text_formatter = TextFormatter()
        self.text_comparator = TextComparator()
        self.file_handler = FileHandler()
        
        # 多标签页管理
        self.editor_tabs = []  # 存储所有编辑器标签页
        self.current_file_paths = {}  # 存储每个标签页的文件路径
        self.current_editor = None  # 当前活动的编辑器
        
        # 搜索对话框
        self.search_dialog = None
        

        
        self.settings = QSettings('TextFormatter', 'TextFormatterApp')
        
        self.init_ui()
        self.setup_menus()
        self.setup_toolbar()
        self.setup_statusbar()
        self.load_settings()
        
    def init_ui(self):
        """初始化用户界面"""
        self.setWindowTitle("文本格式化工具")
        self.setGeometry(100, 100, 1200, 800)
        
        # 创建中央部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 创建主布局
        main_layout = QHBoxLayout(central_widget)
        
        # 创建分割器
        self.splitter = QSplitter(Qt.Orientation.Horizontal)
        main_layout.addWidget(self.splitter)
        
        # 左侧：可收缩的格式化面板
        self.format_panel = self.create_collapsible_format_panel()
        self.splitter.addWidget(self.format_panel)
        
        # 右侧：标签页
        self.tab_widget = QTabWidget()
        self.tab_widget.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
        self.splitter.addWidget(self.tab_widget)
        
        # 设置分割器比例
        self.splitter.setSizes([300, 900])
        
        # 创建文本编辑器标签页
        self.create_text_editor_tab()
        self.create_diff_viewer_tab()
        
    def create_collapsible_format_panel(self):
        """创建可收缩的格式化面板"""
        # 创建主容器
        container = QWidget()
        container.setMaximumWidth(350)
        container.setMinimumWidth(200)
        
        # 创建主布局
        layout = QVBoxLayout(container)
        
        # 创建标题栏
        title_bar = self.create_panel_title_bar()
        layout.addWidget(title_bar)
        
        # 创建滚动区域
        scroll_area = QScrollArea()
        scroll_area.setWidgetResizable(True)
        scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
        scroll_area.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAsNeeded)
        
        # 创建内容面板
        content_panel = self.create_format_panel_content()
        scroll_area.setWidget(content_panel)
        
        layout.addWidget(scroll_area)
        
        return container
    
    def create_panel_title_bar(self):
        """创建面板标题栏"""
        title_bar = QWidget()
        title_bar.setStyleSheet("background-color: #f0f0f0; border-bottom: 1px solid #ccc;")
        title_bar.setFixedHeight(30)
        
        layout = QHBoxLayout(title_bar)
        layout.setContentsMargins(5, 0, 5, 0)
        
        # 标题
        title_label = QLabel("格式化工具")
        title_label.setStyleSheet("font-weight: bold;")
        layout.addWidget(title_label)
        
        layout.addStretch()
        
        # 收缩/展开按钮
        self.collapse_btn = QPushButton("◀")
        self.collapse_btn.setFixedSize(20, 20)
        self.collapse_btn.setStyleSheet("QPushButton { border: none; background: transparent; }")
        self.collapse_btn.clicked.connect(self.toggle_panel)
        layout.addWidget(self.collapse_btn)
        
        return title_bar
    
    def create_format_panel_content(self):
        """创建格式化面板内容"""
        panel = QWidget()
        layout = QVBoxLayout(panel)
        
        # 文件操作组
        file_group = QGroupBox("文件操作")
        file_layout = QVBoxLayout(file_group)
        
        self.open_btn = QPushButton("打开文件")
        self.save_btn = QPushButton("保存文件")
        self.save_as_btn = QPushButton("另存为")
        
        file_layout.addWidget(self.open_btn)
        file_layout.addWidget(self.save_btn)
        file_layout.addWidget(self.save_as_btn)
        
        # 连接信号
        self.open_btn.clicked.connect(self.open_file)
        self.save_btn.clicked.connect(self.save_file)
        self.save_as_btn.clicked.connect(self.save_file_as)
        
        # 基础格式化组
        basic_group = QGroupBox("基础格式化")
        basic_layout = QVBoxLayout(basic_group)
        
        # 大小写转换
        case_layout = QHBoxLayout()
        case_layout.addWidget(QLabel("大小写:"))
        self.case_combo = QComboBox()
        self.case_combo.addItems(["保持不变", "全大写", "全小写", "首字母大写", "驼峰命名", "下划线命名", "短横线命名"])
        case_layout.addWidget(self.case_combo)
        self.case_btn = QPushButton("转换")
        case_layout.addWidget(self.case_btn)
        basic_layout.addLayout(case_layout)
        
        # 空格处理
        space_layout = QHBoxLayout()
        space_layout.addWidget(QLabel("空格:"))
        self.remove_spaces_btn = QPushButton("去除多余空格")
        space_layout.addWidget(self.remove_spaces_btn)
        basic_layout.addLayout(space_layout)
        
        # 缩进处理
        indent_layout = QHBoxLayout()
        indent_layout.addWidget(QLabel("缩进:"))
        self.indent_spin = QSpinBox()
        self.indent_spin.setRange(0, 8)
        self.indent_spin.setValue(4)
        indent_layout.addWidget(self.indent_spin)
        self.add_indent_btn = QPushButton("添加")
        self.remove_indent_btn = QPushButton("去除")
        indent_layout.addWidget(self.add_indent_btn)
        indent_layout.addWidget(self.remove_indent_btn)
        basic_layout.addLayout(indent_layout)
        
        # 连接信号
        self.case_btn.clicked.connect(self.format_case)
        self.remove_spaces_btn.clicked.connect(self.remove_extra_spaces)
        self.add_indent_btn.clicked.connect(self.add_indentation)
        self.remove_indent_btn.clicked.connect(self.remove_indentation)
        
        # 代码格式化组
        code_group = QGroupBox("代码格式化")
        code_layout = QVBoxLayout(code_group)
        
        # 语言选择
        lang_layout = QHBoxLayout()
        lang_layout.addWidget(QLabel("语言:"))
        self.lang_combo = QComboBox()
        self.lang_combo.addItems(["python", "javascript", "json", "xml", "html", "css", "sql"])
        lang_layout.addWidget(self.lang_combo)
        self.format_code_btn = QPushButton("格式化")
        lang_layout.addWidget(self.format_code_btn)
        code_layout.addLayout(lang_layout)
        
        # JSON操作
        json_layout = QHBoxLayout()
        self.format_json_btn = QPushButton("格式化JSON")
        self.minify_json_btn = QPushButton("压缩JSON")
        json_layout.addWidget(self.format_json_btn)
        json_layout.addWidget(self.minify_json_btn)
        code_layout.addLayout(json_layout)
        
        # 连接信号
        self.format_code_btn.clicked.connect(self.format_code)
        self.format_json_btn.clicked.connect(self.format_json)
        self.minify_json_btn.clicked.connect(self.minify_json)
        
        # 文本对齐组
        align_group = QGroupBox("文本对齐")
        align_layout = QVBoxLayout(align_group)
        
        # 对齐方式
        align_btn_layout = QHBoxLayout()
        self.left_align_btn = QPushButton("左对齐")
        self.center_align_btn = QPushButton("居中")
        self.right_align_btn = QPushButton("右对齐")
        align_btn_layout.addWidget(self.left_align_btn)
        align_btn_layout.addWidget(self.center_align_btn)
        align_btn_layout.addWidget(self.right_align_btn)
        align_layout.addLayout(align_btn_layout)
        
        # 行宽设置
        width_layout = QHBoxLayout()
        width_layout.addWidget(QLabel("行宽:"))
        self.width_spin = QSpinBox()
        self.width_spin.setRange(20, 200)
        self.width_spin.setValue(80)
        width_layout.addWidget(self.width_spin)
        self.word_wrap_btn = QPushButton("自动换行")
        width_layout.addWidget(self.word_wrap_btn)
        align_layout.addLayout(width_layout)
        
        # 连接信号
        self.left_align_btn.clicked.connect(lambda: self.align_text('left'))
        self.center_align_btn.clicked.connect(lambda: self.align_text('center'))
        self.right_align_btn.clicked.connect(lambda: self.align_text('right'))
        self.word_wrap_btn.clicked.connect(self.word_wrap)
        
        # 添加到主布局
        layout.addWidget(file_group)
        layout.addWidget(basic_group)
        layout.addWidget(code_group)
        layout.addWidget(align_group)
        layout.addStretch()
        
        return panel
    
    def create_text_editor_tab(self):
        """创建文本编辑器标签页"""
        # 创建编辑器标签页容器
        self.editor_tab_widget = QTabWidget()
        self.editor_tab_widget.setTabsClosable(True)  # 允许关闭标签页
        self.editor_tab_widget.setMovable(True)  # 允许拖拽标签页
        self.editor_tab_widget.tabCloseRequested.connect(self.close_editor_tab)
        self.editor_tab_widget.currentChanged.connect(self.on_editor_tab_changed)
        
        # 添加第一个编辑器
        self.add_new_editor_tab()
        
        self.tab_widget.addTab(self.editor_tab_widget, "文本编辑器")
        
    def create_diff_viewer_tab(self):
        """创建文本比较标签页"""
        self.diff_viewer = DiffViewer()
        self.tab_widget.addTab(self.diff_viewer, "文本比较")
    
    def add_new_editor_tab(self, file_path=None, content=None):
        """添加新的编辑器标签页"""
        editor = TextEditor()
        tab_index = self.editor_tab_widget.addTab(editor, "新建文档")
        
        # 存储编辑器引用
        self.editor_tabs.append(editor)
        
        # 如果有文件路径，设置标题
        if file_path:
            self.current_file_paths[tab_index] = file_path
            file_name = os.path.basename(file_path)
            self.editor_tab_widget.setTabText(tab_index, file_name)
        
        # 如果有内容，设置文本
        if content:
            editor.setPlainText(content)
        
        # 切换到新标签页
        self.editor_tab_widget.setCurrentIndex(tab_index)
        self.current_editor = editor
        
        return tab_index
    
    def close_editor_tab(self, index):
        """关闭编辑器标签页"""
        if self.editor_tab_widget.count() <= 1:
            # 至少保留一个标签页
            return
        
        # 检查是否有未保存的更改
        editor = self.editor_tabs[index]
        if editor.document().isModified():
            reply = QMessageBox.question(
                self, "保存更改", 
                "文档已修改，是否保存更改？",
                QMessageBox.StandardButton.Save | 
                QMessageBox.StandardButton.Discard | 
                QMessageBox.StandardButton.Cancel
            )
            
            if reply == QMessageBox.StandardButton.Save:
                # 临时保存当前编辑器状态
                temp_editor = self.current_editor
                temp_index = self.editor_tab_widget.currentIndex()
                
                # 切换到要关闭的标签页
                self.editor_tab_widget.setCurrentIndex(index)
                self.current_editor = editor
                
                # 保存文件
                self.save_file()
                
                # 恢复原来的编辑器
                self.editor_tab_widget.setCurrentIndex(temp_index)
                self.current_editor = temp_editor
                
                if reply == QMessageBox.StandardButton.Cancel:
                    return
            elif reply == QMessageBox.StandardButton.Cancel:
                return
        
        # 移除编辑器引用
        self.editor_tabs.pop(index)
        if index in self.current_file_paths:
            del self.current_file_paths[index]
        
        # 关闭标签页
        self.editor_tab_widget.removeTab(index)
        
        # 更新当前编辑器
        if self.editor_tab_widget.count() > 0:
            current_index = self.editor_tab_widget.currentIndex()
            self.current_editor = self.editor_tabs[current_index]
    
    def on_editor_tab_changed(self, index):
        """编辑器标签页切换事件"""
        if 0 <= index < len(self.editor_tabs):
            self.current_editor = self.editor_tabs[index]
            # 更新窗口标题
            self.update_window_title()
    
    def update_window_title(self):
        """更新窗口标题"""
        if self.current_editor and self.tab_widget.currentIndex() == 0:
            current_index = self.editor_tab_widget.currentIndex()
            if current_index in self.current_file_paths:
                file_path = self.current_file_paths[current_index]
                self.setWindowTitle(f"文本格式化工具 - {os.path.basename(file_path)}")
            else:
                self.setWindowTitle("文本格式化工具 - 新建文档")
        else:
            self.setWindowTitle("文本格式化工具")
    

    
    def setup_menus(self):
        """设置菜单栏"""
        menubar = self.menuBar()
        
        # 文件菜单
        file_menu = menubar.addMenu("文件")
        
        new_tab_action = QAction("新建标签页", self)
        new_tab_action.setShortcut(QKeySequence("Ctrl+T"))
        new_tab_action.triggered.connect(self.new_tab)
        file_menu.addAction(new_tab_action)
        
        open_action = QAction("打开", self)
        open_action.setShortcut(QKeySequence.StandardKey.Open)
        open_action.triggered.connect(self.open_file)
        file_menu.addAction(open_action)
        
        save_action = QAction("保存", self)
        save_action.setShortcut(QKeySequence.StandardKey.Save)
        save_action.triggered.connect(self.save_file)
        file_menu.addAction(save_action)
        
        save_as_action = QAction("另存为", self)
        save_as_action.setShortcut(QKeySequence.StandardKey.SaveAs)
        save_as_action.triggered.connect(self.save_file_as)
        file_menu.addAction(save_as_action)
        
        file_menu.addSeparator()
        
        exit_action = QAction("退出", self)
        exit_action.setShortcut(QKeySequence.StandardKey.Quit)
        exit_action.triggered.connect(self.close)
        file_menu.addAction(exit_action)
        
        # 编辑菜单
        edit_menu = menubar.addMenu("编辑")
        
        undo_action = QAction("撤销", self)
        undo_action.setShortcut(QKeySequence.StandardKey.Undo)
        undo_action.triggered.connect(self.undo)
        edit_menu.addAction(undo_action)
        
        redo_action = QAction("重做", self)
        redo_action.setShortcut(QKeySequence.StandardKey.Redo)
        redo_action.triggered.connect(self.redo)
        edit_menu.addAction(redo_action)
        
        edit_menu.addSeparator()
        
        select_all_action = QAction("全选", self)
        select_all_action.setShortcut(QKeySequence.StandardKey.SelectAll)
        select_all_action.triggered.connect(self.select_all)
        edit_menu.addAction(select_all_action)
        
        edit_menu.addSeparator()
        
        # 添加格式化快捷键
        format_action = QAction("快速格式化", self)
        format_action.setShortcut(QKeySequence("Ctrl+Shift+F"))
        format_action.triggered.connect(self.quick_format)
        edit_menu.addAction(format_action)
        
        # 工具菜单
        tools_menu = menubar.addMenu("工具")
        
        batch_process_action = QAction("批量处理", self)
        batch_process_action.triggered.connect(self.batch_process)
        tools_menu.addAction(batch_process_action)
        
        encoding_convert_action = QAction("编码转换", self)
        encoding_convert_action.triggered.connect(self.convert_encoding)
        tools_menu.addAction(encoding_convert_action)
        
        # 帮助菜单
        help_menu = menubar.addMenu("帮助")
        
        about_action = QAction("关于", self)
        about_action.triggered.connect(self.show_about)
        help_menu.addAction(about_action)
        
    def setup_toolbar(self):
        """设置工具栏"""
        toolbar = self.addToolBar("主工具栏")
        toolbar.setMovable(False)
        toolbar.setStyleSheet("""
            QToolBar {
                spacing: 8px;
                padding: 4px;
                background: #f8f9fa;
                border-bottom: 1px solid #e9ecef;
            }
            QToolButton {
                border: 1px solid transparent;
                border-radius: 3px;
                padding: 4px 8px;
                background: transparent;
                font-size: 12px;
                min-height: 20px;
            }
            QToolButton:hover {
                background: #e3f2fd;
                border-color: #2196f3;
            }
            QToolButton:pressed {
                background: #bbdefb;
            }
        """)
        
        # 文件操作
        new_tab_action = QAction("新建标签页", self)
        new_tab_action.setStatusTip("创建新的编辑器标签页")
        new_tab_action.triggered.connect(self.new_tab)
        toolbar.addAction(new_tab_action)
        
        open_action = QAction("打开", self)
        open_action.triggered.connect(self.open_file)
        toolbar.addAction(open_action)
        
        save_action = QAction("保存", self)
        save_action.triggered.connect(self.save_file)
        toolbar.addAction(save_action)
        
        toolbar.addSeparator()
        
        # 编辑操作
        undo_action = QAction("撤销", self)
        undo_action.setShortcut(QKeySequence.StandardKey.Undo)
        undo_action.triggered.connect(self.undo)
        toolbar.addAction(undo_action)
        
        redo_action = QAction("重做", self)
        redo_action.setShortcut(QKeySequence.StandardKey.Redo)
        redo_action.triggered.connect(self.redo)
        toolbar.addAction(redo_action)
        
        toolbar.addSeparator()
        
        # 搜索操作
        find_action = QAction("查找", self)
        find_action.setShortcut(QKeySequence.StandardKey.Find)
        find_action.triggered.connect(self.show_search_dialog)
        toolbar.addAction(find_action)
        
        replace_action = QAction("替换", self)
        replace_action.setShortcut(QKeySequence.StandardKey.Replace)
        replace_action.triggered.connect(self.show_replace_dialog)
        toolbar.addAction(replace_action)
        
        toolbar.addSeparator()
        
        # 格式化操作
        format_action = QAction("格式化", self)
        format_action.triggered.connect(self.quick_format)
        toolbar.addAction(format_action)
        
        toolbar.addSeparator()
        
        # 比较选项下拉框 - 优化样式和位置
        options_label = QLabel("比较选项:")
        options_label.setStyleSheet("margin-right: 5px; font-weight: bold; color: #333;")
        toolbar.addWidget(options_label)
        
        self.diff_options_combo = QComboBox()
        self.diff_options_combo.addItems([
            "标准比较",
            "忽略大小写",
            "忽略空格",
            "忽略空行",
            "忽略大小写+空格",
            "忽略大小写+空行",
            "忽略空格+空行",
            "忽略大小写+空格+空行"
        ])
        self.diff_options_combo.setMaximumWidth(180)
        self.diff_options_combo.setMinimumWidth(120)
        self.diff_options_combo.setStyleSheet("""
            QComboBox {
                border: 2px solid #ddd;
                border-radius: 4px;
                padding: 4px 8px;
                background: white;
                font-size: 12px;
                min-height: 20px;
            }
            QComboBox:hover {
                border-color: #0078d4;
            }
            QComboBox:focus {
                border-color: #0078d4;
                outline: none;
            }
            QComboBox::drop-down {
                border: none;
                width: 20px;
            }
            QComboBox::down-arrow {
                image: none;
                border-left: 5px solid transparent;
                border-right: 5px solid transparent;
                border-top: 5px solid #666;
                margin-right: 5px;
            }
            QComboBox::down-arrow:hover {
                border-top-color: #0078d4;
            }
        """)
        toolbar.addWidget(self.diff_options_combo)
        
        # 比较操作 - 优化样式
        diff_compare_action = QAction("比较", self)
        diff_compare_action.setStatusTip("执行文本比较")
        diff_compare_action.triggered.connect(self.diff_compare)
        toolbar.addAction(diff_compare_action)
        
        diff_merge_action = QAction("合并", self)
        diff_merge_action.setStatusTip("合并文本差异")
        diff_merge_action.triggered.connect(self.diff_merge)
        toolbar.addAction(diff_merge_action)
        
        diff_clear_action = QAction("清空", self)
        diff_clear_action.setStatusTip("清空比较内容")
        diff_clear_action.triggered.connect(self.diff_clear)
        toolbar.addAction(diff_clear_action)
        
        toolbar.addSeparator()
        

        
        toolbar.addSeparator()
        
        # 面板控制
        panel_action = QAction("显示/隐藏面板", self)
        panel_action.triggered.connect(self.toggle_panel)
        toolbar.addAction(panel_action)
        
    def setup_statusbar(self):
        """设置状态栏"""
        self.statusbar = self.statusBar()
        self.progress_bar = QProgressBar()
        self.progress_bar.setVisible(False)
        self.statusbar.addPermanentWidget(self.progress_bar)
        
    def load_settings(self):
        """加载设置"""
        geometry = self.settings.value('geometry')
        if geometry:
            self.restoreGeometry(geometry)
            
        window_state = self.settings.value('windowState')
        if window_state:
            self.restoreState(window_state)
        

    
    def save_settings(self):
        """保存设置"""
        self.settings.setValue('geometry', self.saveGeometry())
        self.settings.setValue('windowState', self.saveState())
    
    def closeEvent(self, event):
        """关闭事件"""
        self.save_settings()
        event.accept()
    
    # 文件操作
    def new_tab(self):
        """新建标签页"""
        self.add_new_editor_tab()
        self.statusbar.showMessage("已创建新标签页")
    
    def open_file(self):
        """打开文件"""
        file_path, _ = QFileDialog.getOpenFileName(
            self, "打开文件", "", 
            "文本文件 (*.txt *.md *.py *.js *.json *.xml *.html *.css *.sql);;所有文件 (*)"
        )
        
        if file_path:
            try:
                content = self.file_handler.read_file(file_path)
                # 在新标签页中打开文件
                tab_index = self.add_new_editor_tab(file_path, content)
                self.current_file_paths[tab_index] = file_path
                self.statusbar.showMessage(f"已打开: {file_path}")
            except Exception as e:
                QMessageBox.critical(self, "错误", f"无法打开文件: {str(e)}")
    
    def save_file(self):
        """保存文件"""
        if not self.current_editor:
            return
            
        current_index = self.editor_tab_widget.currentIndex()
        if current_index in self.current_file_paths:
            file_path = self.current_file_paths[current_index]
            try:
                content = self.current_editor.toPlainText()
                self.file_handler.write_file(file_path, content)
                self.current_editor.document().setModified(False)
                self.statusbar.showMessage(f"已保存: {file_path}")
            except Exception as e:
                QMessageBox.critical(self, "错误", f"无法保存文件: {str(e)}")
        else:
            self.save_file_as()
    
    def save_file_as(self):
        """另存为"""
        if not self.current_editor:
            return
            
        file_path, _ = QFileDialog.getSaveFileName(
            self, "另存为", "", 
            "文本文件 (*.txt);;Markdown (*.md);;Python (*.py);;JavaScript (*.js);;JSON (*.json);;XML (*.xml);;HTML (*.html);;CSS (*.css);;SQL (*.sql);;所有文件 (*)"
        )
        
        if file_path:
            try:
                content = self.current_editor.toPlainText()
                self.file_handler.write_file(file_path, content)
                
                # 更新当前标签页的文件路径和标题
                current_index = self.editor_tab_widget.currentIndex()
                self.current_file_paths[current_index] = file_path
                file_name = os.path.basename(file_path)
                self.editor_tab_widget.setTabText(current_index, file_name)
                self.current_editor.document().setModified(False)
                
                self.update_window_title()
                self.statusbar.showMessage(f"已保存: {file_path}")
            except Exception as e:
                QMessageBox.critical(self, "错误", f"无法保存文件: {str(e)}")
    
    # 格式化操作
    def format_case(self):
        """大小写转换"""
        if not self.current_editor:
            return
        text = self.current_editor.toPlainText()
        case_type = self.case_combo.currentText()
        
        case_map = {
            "全大写": "upper",
            "全小写": "lower", 
            "首字母大写": "title",
            "驼峰命名": "camel",
            "下划线命名": "snake",
            "短横线命名": "kebab"
        }
        
        if case_type in case_map:
            formatted_text = self.text_formatter.format_case(text, case_map[case_type])
            self.update_text_with_undo(formatted_text)
    
    def update_text_with_undo(self, new_text):
        """更新文本并保持撤销历史"""
        if not self.current_editor:
            return
        cursor = self.current_editor.textCursor()
        cursor.beginEditBlock()
        cursor.select(cursor.SelectionType.Document)
        cursor.insertText(new_text)
        cursor.endEditBlock()
    
    def remove_extra_spaces(self):
        """去除多余空格"""
        if not self.current_editor:
            return
        text = self.current_editor.toPlainText()
        formatted_text = self.text_formatter.remove_extra_spaces(text)
        self.update_text_with_undo(formatted_text)
    
    def add_indentation(self):
        """添加缩进"""
        if not self.current_editor:
            return
        text = self.current_editor.toPlainText()
        spaces = self.indent_spin.value()
        formatted_text = self.text_formatter.add_indentation(text, spaces)
        self.update_text_with_undo(formatted_text)
    
    def remove_indentation(self):
        """去除缩进"""
        if not self.current_editor:
            return
        text = self.current_editor.toPlainText()
        formatted_text = self.text_formatter.remove_indentation(text)
        self.update_text_with_undo(formatted_text)
    
    def format_code(self):
        """代码格式化"""
        if not self.current_editor:
            return
        text = self.current_editor.toPlainText()
        language = self.lang_combo.currentText()
        formatted_text = self.text_formatter.format_code(text, language)
        self.update_text_with_undo(formatted_text)
    
    def format_json(self):
        """JSON格式化"""
        if not self.current_editor:
            return
        text = self.current_editor.toPlainText()
        formatted_text = self.text_formatter.format_json(text)
        self.update_text_with_undo(formatted_text)
    
    def minify_json(self):
        """JSON压缩"""
        if not self.current_editor:
            return
        text = self.current_editor.toPlainText()
        formatted_text = self.text_formatter.minify_json(text)
        self.update_text_with_undo(formatted_text)
    
    def align_text(self, alignment):
        """文本对齐"""
        if not self.current_editor:
            return
        text = self.current_editor.toPlainText()
        width = self.width_spin.value()
        formatted_text = self.text_formatter.align_text(text, alignment, width)
        self.update_text_with_undo(formatted_text)
    
    def word_wrap(self):
        """自动换行"""
        if not self.current_editor:
            return
        text = self.current_editor.toPlainText()
        width = self.width_spin.value()
        formatted_text = self.text_formatter.word_wrap(text, width)
        self.update_text_with_undo(formatted_text)
    
    def quick_format(self):
        """快速格式化"""
        if not self.current_editor:
            return
        text = self.current_editor.toPlainText()
        # 自动检测并格式化
        if text.strip().startswith('{') and text.strip().endswith('}'):
            formatted_text = self.text_formatter.format_json(text)
        elif text.strip().startswith('<') and text.strip().endswith('>'):
            formatted_text = self.text_formatter.format_xml(text)
        else:
            formatted_text = self.text_formatter.remove_extra_spaces(text)
        
        self.update_text_with_undo(formatted_text)
    
    # 编辑操作
    def undo(self):
        """撤销"""
        if self.current_editor:
            self.current_editor.undo()
    
    def redo(self):
        """重做"""
        if self.current_editor:
            self.current_editor.redo()
    
    def select_all(self):
        """全选"""
        if self.current_editor:
            self.current_editor.selectAll()
    
    # 工具操作
    def batch_process(self):
        """批量处理"""
        folder_path = QFileDialog.getExistingDirectory(self, "选择文件夹")
        if folder_path:
            # 这里可以实现批量处理逻辑
            QMessageBox.information(self, "批量处理", "批量处理功能待实现")
    
    def convert_encoding(self):
        """编码转换"""
        # 这里可以实现编码转换对话框
        QMessageBox.information(self, "编码转换", "编码转换功能待实现")
    
    def show_about(self):
        """显示关于对话框"""
        QMessageBox.about(self, "关于", 
                         "文本格式化工具 v1.0\n\n"
                         "一个功能强大的文本格式化和比较工具")
    
    def toggle_panel(self):
        """切换面板显示/隐藏"""
        if self.format_panel.isVisible():
            self.format_panel.hide()
            self.collapse_btn.setText("▶")
            # 隐藏面板时，将全部空间给编辑器
            self.splitter.setSizes([0, self.splitter.width()])
        else:
            self.format_panel.show()
            self.collapse_btn.setText("◀")
            # 显示面板时，调整比例
            if self.tab_widget.currentIndex() == 1:  # 文本比较视图
                self.adjust_splitter_for_diff_view()
            else:  # 文本编辑器视图
                self.splitter.setSizes([300, self.splitter.width() - 300])
    

    
    def adjust_splitter_for_diff_view(self):
        """为文本比较视图调整分割器"""
        # 如果左侧面板可见，设置合适的比例
        if self.format_panel.isVisible():
            total_width = self.splitter.width()
            panel_width = min(300, total_width // 4)  # 面板占1/4或300px
            editor_width = total_width - panel_width
            self.splitter.setSizes([panel_width, editor_width])
        else:
            # 如果面板隐藏，全部空间给编辑器
            self.splitter.setSizes([0, self.splitter.width()])
    
    def diff_compare(self):
        """执行文本比较"""
        if self.tab_widget.currentIndex() == 1:  # 在文本比较标签页
            # 根据工具栏选项设置比较参数
            option = self.diff_options_combo.currentText()
            ignore_case = "忽略大小写" in option
            ignore_whitespace = "忽略空格" in option
            ignore_empty_lines = "忽略空行" in option
            
            self.diff_viewer.set_comparison_options(ignore_case, ignore_whitespace, ignore_empty_lines)
            self.diff_viewer.compare_texts()
    
    def diff_merge(self):
        """执行文本合并"""
        if self.tab_widget.currentIndex() == 1:  # 在文本比较标签页
            self.diff_viewer.merge_texts()
    
    def diff_clear(self):
        """清空文本比较"""
        if self.tab_widget.currentIndex() == 1:  # 在文本比较标签页
            self.diff_viewer.clear_texts()
    
    # 搜索和替换功能
    def show_search_dialog(self):
        """显示搜索对话框"""
        if not self.current_editor:
            return
            
        if not self.search_dialog:
            self.search_dialog = SearchDialog(self)
            self.search_dialog.find_next.connect(self.find_next)
            self.search_dialog.find_previous.connect(self.find_previous)
            self.search_dialog.find_all.connect(self.find_all)
            self.search_dialog.replace.connect(self.replace_text)
            self.search_dialog.replace_all.connect(self.replace_all_text)
        
        self.search_dialog.show()
        self.search_dialog.raise_()
        self.search_dialog.activateWindow()
    
    def show_replace_dialog(self):
        """显示替换对话框"""
        if not self.current_editor:
            return
            
        if not self.search_dialog:
            self.search_dialog = SearchDialog(self)
            self.search_dialog.find_next.connect(self.find_next)
            self.search_dialog.find_previous.connect(self.find_previous)
            self.search_dialog.find_all.connect(self.find_all)
            self.search_dialog.replace.connect(self.replace_text)
            self.search_dialog.replace_all.connect(self.replace_all_text)
        
        # 切换到替换标签页
        self.search_dialog.show()
        self.search_dialog.raise_()
        self.search_dialog.activateWindow()
    
    def find_next(self, search_text, case_sensitive, whole_word):
        """查找下一个"""
        if not self.current_editor:
            return
            
        found = self.current_editor.find_text(search_text, case_sensitive, whole_word, True)
        if found:
            self.search_dialog.set_status(f"找到: {search_text}")
        else:
            self.search_dialog.set_status(f"未找到: {search_text}")
    
    def find_previous(self, search_text, case_sensitive, whole_word):
        """查找上一个"""
        if not self.current_editor:
            return
            
        found = self.current_editor.find_text(search_text, case_sensitive, whole_word, False)
        if found:
            self.search_dialog.set_status(f"找到: {search_text}")
        else:
            self.search_dialog.set_status(f"未找到: {search_text}")
    
    def find_all(self, search_text, case_sensitive, whole_word):
        """查找所有"""
        if not self.current_editor:
            return
            
        matches = self.current_editor.find_all(search_text, case_sensitive, whole_word)
        if matches:
            self.search_dialog.set_status(f"找到 {len(matches)} 个匹配项")
        else:
            self.search_dialog.set_status(f"未找到: {search_text}")
    
    def replace_text(self, search_text, replace_text, case_sensitive, whole_word):
        """替换当前匹配项"""
        if not self.current_editor:
            return
            
        replaced = self.current_editor.replace_text(search_text, replace_text, case_sensitive, whole_word)
        if replaced:
            self.search_dialog.set_status(f"已替换: {search_text} -> {replace_text}")
        else:
            self.search_dialog.set_status(f"未找到匹配项: {search_text}")
    
    def replace_all_text(self, search_text, replace_text, case_sensitive, whole_word):
        """替换所有匹配项"""
        if not self.current_editor:
            return
            
        count = self.current_editor.replace_all(search_text, replace_text, case_sensitive, whole_word)
        if count > 0:
            self.search_dialog.set_status(f"已替换 {count} 个匹配项")
        else:
            self.search_dialog.set_status(f"未找到匹配项: {search_text}") 